#include "app_time.h"

#define SYNCHRONIZE_INTERVAL    (3600 * 1000 * 8) // 8小时

enum {
    TIME_UNINIT,
    TIME_INIT,
};

enum {
    NO_SYNCHRONIZED,
    SYNCHRONIZED,
};

typedef struct {
    unsigned char init;             // 是否已经初始化
    unsigned char synchronized;     // 是否已经同步
    unsigned int last;              // 同步时间
} app_time_t;

static app_time_t sg_app_time;
static void app_time_set_init(void)
{
    app_led_timer_init();
    drv_rtc_init();
    sg_app_time.init = TIME_INIT;
    app_led_timer_deinit();
}

static void app_time_set(int year, int month, int day, int wday, int hour, int min, int sec)
{
    if (sg_app_time.init != TIME_INIT) {
        app_time_set_init();
    }

    rtc_date_time_t set;
    set.date.year   = year - 2000;
    set.date.month  = month & 0xFF;
    set.date.day    = day & 0xFF;
    set.date.wday   = wday & 0xFF;
    set.time.hour   = hour & 0xFF;
    set.time.mins   = min & 0xFF;
    set.time.secs   = sec & 0xFF;
    drv_rtc_SetTime(&set);
}

static void app_time_request_handler(void)
{
    unsigned int interval = sg_app_time.synchronized ? SYNCHRONIZE_INTERVAL : 3000;	//未同步间隔=3s
    if (time_after(app_sys_ticks, sg_app_time.last + interval)) {
        if (dev_obj->tuya_net == TUYA_NET_OK) {
            sg_app_time.last = app_sys_ticks;
            app_uart_tx_wifi_lmt_noti();
        }
    }
}

void app_time_task(void)
{
    if (sg_app_time.init != TIME_INIT) {
        sg_app_time.synchronized = NO_SYNCHRONIZED;	//初次上电处于未同步
        app_time_set_init();
    }

    drv_rtc_update();
    app_time_request_handler();
}

void app_time_cb_handler(const unsigned char *data, unsigned short length)
{
    rtc_date_time_t dat = {0x00};
    dat.date.year   = data[0];
    dat.date.month  = data[1];
    dat.date.day    = data[2];
    dat.time.hour   = data[3];
    dat.time.mins   = data[4];
    dat.time.secs   = data[5];
    dat.date.wday   = data[6];

    drv_rtc_SetTime(&dat);
    sg_app_time.synchronized = SYNCHRONIZED;
}